﻿
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO; 
using System.Text; 
using System.Windows.Forms;
 
using DevelopAssistant.Common;
using DevelopAssistant.Core.Contents;
using DevelopAssistant.Core.DBMS;
using DevelopAssistant.Core.ToolBar;
using DevelopAssistant.Core.ToolBox;
using ICSharpCode.WinFormsUI.Theme;
using ICSharpCode.WinFormsUI.Docking;
using DevelopAssistant.AddIn; 

namespace DevelopAssistant.Core
{
    using DevelopAssistant.Core.Properties;
    using DevelopAssistant.Service;
    using ICSharpCode.WinFormsUI.Controls;

    public partial class MainForm : ICSharpCode.WinFormsUI.Forms.BaseForm //Form //
    {        
        string configFile = string.Empty;
        string loginName = string.Empty;
        string serverName = string.Empty;

        private StartForm startForm = null;
        private SnippetBar snippetBar = null;
        private MenuBar MenuBar = null;       
               
        private HomeContent homeContent = null;

        private StringPlus m_strPlus = new StringPlus();

        private DeserializeDockContent m_deserializeDockContent;
        private Dictionary<string, int> m_mainmenuDictionary;
        public SnippetBar SnippetBar
        {
            get { return snippetBar; }
        }

        private DataBaseServer _connectedDataBaseServer = null;
        public DataBaseServer ConnectedDataBaseServer
        {
            get { return _connectedDataBaseServer; }
            set
            {
                if (_connectedDataBaseServer != value)
                {
                    _connectedDataBaseServer = value;
                    serverName = m_strPlus.GetCnShortStr(this._connectedDataBaseServer.Server, 2, true) + " " + this._connectedDataBaseServer.DataBaseName;
                }               
            }
        }

        private string _productName;
        public new string ProductName
        {
            get { return _productName; }
            set { _productName = value; }
        }

        private string _productVersion;
        public new string ProductVersion
        {
            get { return _productVersion; }
            set { _productVersion = value; }
        }

        private string _newVersion;
        public string NewVersion
        {
            get { return _newVersion; }
            set { _newVersion = value; }
        }

        public MainForm()
        {
            InitializeComponent();
            InitializeControl();
            InitializeIntellisenseSettings();
        }

        public MainForm(StartForm startForm)
            : this()
        {
            this.startForm = startForm;
            this.startForm.XTheme = this.XTheme;
            this.SystemMenu = SystemContextMenu;
            this.ShowIconMenu = true;
        }

        private void InitializeIntellisenseSettings()
        {
            AppSettings.NewOpenQueryDocument = true;
            AppSettings.EditorSettings = new TSQLEditorSettings() { EnableIntellisense = true, EnableDataBaseTran = true };
            AppSettings.EditorSettings.EditorFont = new Font("Courier New", 10.0f);
            AppSettings.EditorSettings.EnableDataBaseTran = false;
            AppSettings.WindowFont = this.Font;//Name = "宋体" Size=9.0
        }

        private void InitializeControl()
        {
            m_mainmenuDictionary = new Dictionary<string, int>();
            for (int i = 0, len = MainMenu.Items.Count; i < len; i++)
            {
                var item= MainMenu.Items[i];
                m_mainmenuDictionary.Add(item.Name.Replace("menuItem", ""), i);
            }

            configFile = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "DockPanel.temp.config");

            m_deserializeDockContent = new DeserializeDockContent(GetContentFromPersistString);

            dockPanel.DocumentStyle = DocumentStyle.DockingMdi;
            dockPanel.ShowDocumentIcon = true;

            if (File.Exists(configFile))
            {
                System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
                xmlDoc.Load(configFile);
                System.Xml.XmlNode ThemeConfigure = xmlDoc.SelectSingleNode("//Theme");
                if (ThemeConfigure != null)
                {
                    string mainformTheme = ThemeConfigure.Attributes["MainFormTheme"].Value;
                    string dockcontentTheme = ThemeConfigure.Attributes["DockPanelTheme"].Value;
                    setSystemTheme(mainformTheme, dockcontentTheme);
                }                
            }
            else
            {
                snippetBar = new SnippetBar()
                {
                    CloseButtonVisible = false,
                    AutoHidePortion = 196,
                    IsHidden = false,
                };
                snippetBar.Show(dockPanel, DockState.DockLeftAutoHide);

                MenuBar = new MenuBar(this,contextMenuStrip3)
                {
                    CloseButtonVisible = false,
                    AutoHidePortion = 196
                };
                MenuBar.Show(dockPanel, DockState.DockLeft);

                homeContent = new HomeContent()
                {
                    CloseButtonVisible = false,
                    AllowEndUserDocking = false,
                    TabPageContextMenuStrip = contextMenuStrip2
                };
                homeContent.Show(dockPanel);
            }

            dockPanel.WindowTheme = XTheme;
            dockPanel.ActiveContentChanged += dockPanel_ActiveContentChanged;      

        }

        private void InitalizeWorkArea()
        {            
            this.MinimumSize = new Size(1280, 700);
            Rectangle WorkArea = new Rectangle((this.MaximizedBounds.Width - this.Width)/2,
                (this.MaximizedBounds.Height - this.Height) / 2,
                this.Width,
                this.Height);
            this.SetBoundsCore(WorkArea);            
            this.WindowState = FormWindowState.Maximized;
        }

        private void InitializeInfo()
        {            
            menuItemTools.DropDownItems.Clear();
            menuItemFunction.DropDownItems.Clear();

            System.Threading.Thread th = new System.Threading.Thread(() =>
            {
                this.Invoke(new MethodInvoker(delegate()
                {
                    MainMenu.Enabled = false;
                    SysStatusInfo.Text = "初始化...";
                }));

                string message = string.Empty;

                string AssemblyName = "DevelopAssistant.Core";
                //多线程操作 ， 检查版本 ， 加载插件

                var version = Version_on_Manager.Instance.Load(ref message);
                if (ProductVersion != version)
                {
                    NewVersion = version;
                    if (message == "Request Version Success" ||
                        message == "Yes" || message == "Y")
                    {
                        QuestionVersion();
                    }
                }

                var list = Plug_in_Manager.Instance.Load(ref message);

                System.Threading.Thread.Sleep(200);

                if (this.IsHandleCreated)
                {
                    int count = this.contextMenuStrip3.Items.Count;
                    for (int i = 0; i < this.contextMenuStrip3.Items.Count; i++)
                    {
                        NToolStripMenuItem item = (NToolStripMenuItem)this.contextMenuStrip3.Items[i];
                        if (item.AddIn != null)
                        {
                            this.statusBar.Invoke(new MethodInvoker(delegate()
                            {
                                this.contextMenuStrip3.Items.Remove(item);
                            }));
                        }
                    } 
                }                                              

                foreach (var li in list)
                {
                    int OrderIndex = 0;
                    string PositionAt = li.Position.TrimStart('/');

                    ///DevelopAssistant/MainForm/MainMenu/Function

                    string[] MenuItemPositionSections = PositionAt.Split('/');
                    if (MenuItemPositionSections[2] == "MainMenu")
                    {
                        ToolStripMenuItem menu = null;
                        OrderIndex = m_mainmenuDictionary[MenuItemPositionSections[3]];
                        menu = (ToolStripMenuItem)MainMenu.Items[OrderIndex];
                        var item = new ToolStripMenuItem() { Text = li.Text, ToolTipText = li.Tooltip };
                        item.Click += Plugin_MenuItem_Click;

                        if (li.Icon != null)
                        {
                            item.Image = li.Icon;
                        }
                        item.Tag = li;

                        this.Invoke(new MethodInvoker(delegate()
                        {
                            menu.DropDownItems.Add(item);
                        }));

                    }
                    else if (MenuItemPositionSections[2] == "MainToolBar")
                    {
                        ToolStripItem menu = null;
                    }
                    else if (MenuItemPositionSections[2] == "TreeViewMenu")
                    {
                        var index = MenuItemPositionSections[3];
                        var level = MenuItemPositionSections[4];
                        NToolStripMenuItem menu = new NToolStripMenuItem("AddInToolStripMenuItem") { Text = li.Text, Name = li.Name };
                        menu.Index = Int32.Parse(index);
                        menu.Level = Int32.Parse(level);
                        menu.AddIn = li;
                        menu.Position = li.Position;

                        //var item = GetAddinToolStripMenuItem(contextMenuStrip3, li.IdentityID);
                        //if (item != null)
                        //    contextMenuStrip3.Items.Remove(item);
                        contextMenuStrip3.Items.Insert(menu.Index, menu);
                    }

                    li.Initialize(AssemblyName, "MainForm");

                }

                if (MenuBar != null)
                    MenuBar.RefreshTreeMenu(contextMenuStrip3);

                loginName = G_App.SessionInfo.Name;
                this.Invoke(new MethodInvoker(delegate()
                {
                    MainMenu.Enabled = true;
                    SysStatusInfo.Text = "完成";
                    if (startForm != null)
                        startForm.Close();
                }));
            });
            th.IsBackground = true;
            th.Start();
        }

        private void QuestionVersion()
        {
            if (!this.IsHandleCreated)
                return;

            if (this.InvokeRequired)
            {
                string newVersionTip = this.SysStatusInfo.Text;
                this.Invoke(new MethodInvoker(delegate() {

                    this.SysNewVersion.Visible = true;
                    this.SysStatusInfo.Text = "发现 " + NewVersion + "  版本等待更新";
                    this.SysStatusInfo.ForeColor = System.Drawing.Color.Red;

                    if (new MessageDialog(DevelopAssistant.Core.Properties.Resources.question_32px, "发现 " + NewVersion + "  版本等待更新", MessageBoxButtons.OKCancel).ShowDialog(this).Equals(DialogResult.OK))
                    {
                        string application_start_path = Trim(AppDomain.CurrentDomain.BaseDirectory);
                        if (System.IO.File.Exists(string.Format("{0}\\Autoupgrade.EXE", application_start_path)))
                        {
                            System.Diagnostics.Process.Start(string.Format("{0}\\Autoupgrade.EXE", application_start_path));
                            try
                            {
                                System.Threading.Thread.Sleep(100);
                                Application.Exit();
                            }
                            catch (Exception ex)
                            {
                                DevelopAssistant.Common.NLogger.WriteToLine(ex.Message, "错误", DateTime.Now, ex.Source, ex.StackTrace);
                                Environment.Exit(0);
                            }
                        }
                    }

                    this.SysStatusInfo.Text = newVersionTip;
                    this.SysStatusInfo.ForeColor = System.Drawing.Color.Black;
                    this.SysNewVersion.Visible = false;
                
                }));
            }
            
        }

        private string Trim(string input)
        {
            string result = string.Empty;
            if (!string.IsNullOrEmpty(input))
            {
                result = input.Trim().TrimEnd('\\');
            }
            return result;
        }
                
        protected override void OnClosed(EventArgs e)
        {           
            try
            {
                CloseAllContents();
                DockPanelSaveAsXml();             
                Application.Exit();
            }
            catch (Exception ex)
            {
                System.Environment.Exit(0);
            }
        }

        private void dockPanel_ActiveContentChanged(object sender, EventArgs e)
        {
            if (this.ConnectedDataBaseServer != null)
            {
                var dcnt = (DockContent)dockPanel.ActiveContent;
                if (dcnt.GetType().Equals(typeof(QueryDocument)))
                {
                    string connectionID = ((QueryDocument)dcnt).ConnectionID;
                    //string dataBaseType = ((QueryDocument)dcnt).DataBaseType;
                    //string connectionString = ((QueryDocument)dcnt).ConnectionString;
                    DataBaseServerChanged(connectionID);
                }
            }             
        }

        private bool DataBaseServerChanged(string connectionID)
        {
            if (MenuBar != null)
            {
                this.ConnectedDataBaseServer = MenuBar.GetDataBaseServerByConnectionID(connectionID);
                SetQueryFormToolBarItemVisible(true,true);
            }
            return true;
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            InitalizeWorkArea();       
            InitializeInfo();           
        }

        private void Plugin_MenuItem_Click(object sender, EventArgs e)
        {
            var plugin = (AddInBase)((ToolStripMenuItem)sender).Tag;
            ExecuteAddIn(plugin);
        }

        private void setSchema_Click(object sender, System.EventArgs e)
        {
            string mainformTheme = string.Empty;            
            if (sender == MacThemeToolStripMenuItem)
            {
                mainformTheme = "ICSharpCode.WinFormsUI.Theme.ThemeMac";               
            }
            else if (sender == WindowsThemeToolStripMenuItem)
            {
                mainformTheme = "ICSharpCode.WinFormsUI.Theme.ThemeVS2012";                
            }
            else if (sender == BootstrapThemeToolStripMenuItem)
            {
                mainformTheme = "ICSharpCode.WinFormsUI.Theme.ThemeShadow";
            }
            setSystemTheme(mainformTheme);
        }

        private void setSystemTheme(string mainformTheme)
        {
            string dockcontentTheme = string.Empty;
            switch (mainformTheme)
            {
                case "ICSharpCode.WinFormsUI.Theme.ThemeMac":
                    dockcontentTheme = "ICSharpCode.WinFormsUI.Docking.VS2003Theme";
                    break;
                case "ICSharpCode.WinFormsUI.Theme.ThemeVS2012":
                    dockcontentTheme = "ICSharpCode.WinFormsUI.Docking.VS2012LightTheme";
                    break;
                case "ICSharpCode.WinFormsUI.Theme.ThemeShadow":
                    dockcontentTheme = "ICSharpCode.WinFormsUI.Docking.VS2013BlueTheme";
                    break;
            }
            setSystemTheme(mainformTheme, dockcontentTheme);
        }

        private void setSystemTheme(string mainformTheme, string dockcontentTheme)
        {
            dockPanel.SuspendLayout(true);

            CloseAllContents(true);

            switch (mainformTheme)
            {
                case "ICSharpCode.WinFormsUI.Theme.ThemeMac":
                    XTheme = new ThemeMac();                   
                    MacThemeToolStripMenuItem.Checked = true;
                    WindowsThemeToolStripMenuItem.Checked = false;
                    BootstrapThemeToolStripMenuItem.Checked = false;
                    ThemeShowShadow(true);
                    break;
                case "ICSharpCode.WinFormsUI.Theme.ThemeVS2012":
                    XTheme = new ThemeVS2012();                   
                    MacThemeToolStripMenuItem.Checked = false;
                    WindowsThemeToolStripMenuItem.Checked = true;
                    BootstrapThemeToolStripMenuItem.Checked = false;                     
                    break;
                case "ICSharpCode.WinFormsUI.Theme.ThemeVS2013":
                    XTheme = new ThemeVS2012();
                    MacThemeToolStripMenuItem.Checked = false;
                    WindowsThemeToolStripMenuItem.Checked = true;
                    BootstrapThemeToolStripMenuItem.Checked = false;                     
                    break;
                case "ICSharpCode.WinFormsUI.Theme.ThemeShadow":                    
                    XTheme = new ThemeShadow();
                    MacThemeToolStripMenuItem.Checked = false;
                    WindowsThemeToolStripMenuItem.Checked = false;
                    BootstrapThemeToolStripMenuItem.Checked = true;                     
                    ThemeShowShadow(true);
                    break;
                default:
                    XTheme = new ThemeMac();
                    break;
            }

            switch (dockcontentTheme)
            {
                case "ICSharpCode.WinFormsUI.Docking.VS2003Theme":
                    dockPanel.DockPanelTheme = new VS2003Theme();
                    statusBar.BackColor = SystemColors.Control;
                    statusBar.ForeColor = Color.Black;
                    break;
                case "ICSharpCode.WinFormsUI.Docking.VS2012LightTheme":
                    dockPanel.DockPanelTheme = new VS2012LightTheme();
                    statusBar.BackColor = SystemColors.Control;
                    statusBar.ForeColor = Color.Black;
                    break;
                case "ICSharpCode.WinFormsUI.Docking.VS2013BlueTheme":
                    dockPanel.DockPanelTheme = new VS2013BlueTheme();
                    statusBar.BackColor = Color.FromArgb(0xFF, 123, 79, 202);
                    statusBar.ForeColor = Color.White;
                    break; 
            }

            dockPanel.WindowTheme = XTheme;
            AppSettings.WindowTheme = dockPanel.WindowTheme;

            if (File.Exists(configFile))
            {
                dockPanel.LoadFromXml(configFile, m_deserializeDockContent);                
            }
            else
            {
                snippetBar = new SnippetBar()
                {
                    CloseButtonVisible = false,
                    AutoHidePortion = 196,
                    IsHidden = false,
                };
                snippetBar.Show(dockPanel, DockState.DockLeftAutoHide);

                MenuBar = new MenuBar(this,contextMenuStrip3)
                {
                    CloseButtonVisible = false,
                    AutoHidePortion = 196
                };
                MenuBar.Show(dockPanel, DockState.DockLeft);

                homeContent = new HomeContent()
                {
                    CloseButtonVisible = false,
                    AllowEndUserDocking = false,
                    TabPageContextMenuStrip = contextMenuStrip2
                };
                homeContent.Show(dockPanel);

            }

            if (MenuBar != null)
                MenuBar.RefreshTreeMenu();

            dockPanel.ResumeLayout(true, true);
        }

        private void toolBarButtonLogger_Click(object sender, EventArgs e)
        {
            //outputBar outputBar = new outputBar() { Height = 100, AutoHidePortion = 100, Text = "系统日志" };
            //outputBar.Show(dockPanel, DockState.DockBottomAutoHide);
            AddNewContent(new DevelopAssistant.Core.Tabs.LoggerTab(this) { Text = "系统日志" }, "系统日志");
        }

        private void toolBarButtonTheme_Click(object sender, EventArgs e)
        {            
            DevelopAssistant.Core.ToolBox.ThemeDialog dialog =
                new DevelopAssistant.Core.ToolBox.ThemeDialog(AppSettings.WindowTheme);
            if (dialog.ShowDialog(this).Equals(DialogResult.OK))
            {
                setSystemTheme(dialog.ThemeName);
            }
        }

        private void toolBarButtonNewWindow_Click(object sender, EventArgs e)
        {
            AddNewContent(new QueryDocument(this) { Text = "新建查询" }, "新建查询");
        }

        private void toolBarButtonExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void 关闭ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DockContent currentContent = (DockContent)dockPanel.ActiveDocument;
            if (currentContent.Name != "HomeContent")
                CloseContent(currentContent);
        }

        private void 关闭所有ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CloseAllContents();
        }

        private void 关闭其它ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CloseOtherContent();
        }

        private void vs2005ThemeToolStripMenuItem_Click(object sender, EventArgs e)
        {           
            setSchema_Click(sender, e);
        }

        private void vs2012ThemeToolStripMenuItem_Click(object sender, EventArgs e)
        {           
            setSchema_Click(sender, e);
        }

        private void menuItemMaxSize_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Maximized;
        }

        private void menuItemNormalSize_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Normal;
        }

        private void menuItemDefaultWindow_Click(object sender, EventArgs e)
        {
            dockPanel.SuspendLayout(true);

            CloseAllContents(true);
            snippetBar = new SnippetBar()
            {
                CloseButtonVisible = false,
                AutoHidePortion = 196,
                IsHidden = false,
            };
            snippetBar.Show(dockPanel, DockState.DockLeftAutoHide);

            MenuBar = new MenuBar(this,contextMenuStrip3)
            {
                CloseButtonVisible = false,
                AutoHidePortion = 196
            };
            MenuBar.Show(dockPanel, DockState.DockLeft);

            homeContent = new HomeContent()
            {
                CloseButtonVisible = false,
                AllowEndUserDocking = false,
                TabPageContextMenuStrip = contextMenuStrip2
            };
            homeContent.Show(dockPanel);

            dockPanel.ResumeLayout(true, true);

            MenuBar.RefreshTreeMenu();
        }

        private void 文本格式化ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //AddFloatWindow(new TextEditorPad(),"文本格式化");     
        }

        private void toolBarFormat_Click(object sender, EventArgs e)
        {
            DockContent dcnt = GetSelectedContent();
            if (dcnt != null && dcnt.GetType().Equals(typeof(QueryDocument)))
            {
                ((QueryDocument)dcnt).TSQLToFormat();
            }
        }

        private void toolBarExecute_Click(object sender, EventArgs e)
        {
            DockContent dcnt = GetSelectedContent();
            if (dcnt != null && dcnt.GetType().Equals(typeof(QueryDocument)))
            {
                ((QueryDocument)dcnt).TSQLToExecute();
            }
        }

        private void toolBarServers_Click(object sender, EventArgs e)
        {
            var senderText = ((ToolStripItem)sender).Text; 
            AddDataBaseConnection connect = new AddSqlServerConnection(this);

            switch (senderText)
            {
                case "Sql数据库":
                    connect = new AddSqlServerConnection(this);
                    break;
                case "Postgresql数据库":
                    connect = new AddPostgreSqlConnection(this);
                    break;
                case "Sqlite数据库":
                    connect = new AddSqliteServerConnection(this);
                    break;
                case "MySql数据库":
                    connect = new AddMySqlServerConnection(this);
                    break;
            }

            if (connect.ShowDialog(this).Equals(DialogResult.OK))
            {
                string TypeName = connect.GetType().Name;
                AddDataBaseServer(connect.ConnectionName, connect.ConnectionString, connect.ProviderName, connect.AllObjectLoad);
            }

            this.BringToFront();
        }

        private void toolBarCommit_Click(object sender, EventArgs e)
        {
            DockContent dcnt = GetSelectedContent();
            if (dcnt != null && dcnt.GetType().Equals(typeof(QueryDocument)))
            {
                ((QueryDocument)dcnt).TSQLCommit();
            }
        }

        private void toolBarRollback_Click(object sender, EventArgs e)
        {
            DockContent dcnt = GetSelectedContent();
            if (dcnt != null && dcnt.GetType().Equals(typeof(QueryDocument)))
            {
                ((QueryDocument)dcnt).TSQLRollback();
            }
        }
        
        private void toolBarUndo_Click(object sender, EventArgs e)
        {
            DockContent dcnt = GetSelectedContent();
            if (dcnt != null && dcnt.GetType().Equals(typeof(QueryDocument)))
            {
                ((QueryDocument)dcnt).Undo();
            }
        }

        private void toolBarRedo_Click(object sender, EventArgs e)
        {
            DockContent dcnt = GetSelectedContent();
            if (dcnt != null && dcnt.GetType().Equals(typeof(QueryDocument)))
            {
                ((QueryDocument)dcnt).Redo();
            }
        }

        private void toolBarFinder_Click(object sender, EventArgs e)
        {
            DockContent dcnt = GetSelectedContent();
            if (dcnt != null && dcnt.GetType().Equals(typeof(QueryDocument)))
            {
                FindAndReplace frm_FindAndReplace = new FindAndReplace(this, ((QueryDocument)dcnt));
                frm_FindAndReplace.Show(this);
            }
        }

        private void toolButtonStop_Click(object sender, EventArgs e)
        {
            DockContent dcnt = GetSelectedContent();
            if (dcnt != null && dcnt.GetType().Equals(typeof(QueryDocument)))
            {
                ((QueryDocument)dcnt).TSQLStop();
            }
        }

        private void 编辑器设置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DevelopAssistant.Core.ToolBox.TSQLEditorSettings form =
                new DevelopAssistant.Core.ToolBox.TSQLEditorSettings();
            form.ShowDialog(this);             
        }

        private void 关于ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AboutForm aboutForm = new AboutForm(this);
            aboutForm.ShowDialog(this);
        }

        private void 帮助ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            HelpForm helpForm = new HelpForm(this);
            helpForm.ShowDialog(this);
        }

        private void 打开文件ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DockContent dcnt = GetSelectedContent();
            if (dcnt != null && dcnt.GetType().Equals(typeof(QueryDocument)))
            {
                ((QueryDocument)dcnt).OpenSqlFile();
            }
        }

        private void toolBarButtonSave_Click(object sender, EventArgs e)
        {
            DockContent dcnt = GetSelectedContent();
            if (dcnt != null && dcnt.GetType().Equals(typeof(QueryDocument)))
            {
                ((QueryDocument)dcnt).SaveSqlFile();
            }
        }

        private void toolBarButtonToolBox_Click(object sender, EventArgs e)
        {
            AddinToolBoxes toolForm = new AddinToolBoxes();
            if (toolForm.ShowDialog(this).Equals(DialogResult.OK))
            {
                InitializeInfo();
            }
        }

        private void toolBarAddComment_Click(object sender, EventArgs e)
        {
            DockContent dcnt = GetSelectedContent();
            if (dcnt != null && dcnt.GetType().Equals(typeof(QueryDocument)))
            {
                ((QueryDocument)dcnt).Comment(1);
            }
        }

        private void toolBarRemoveComment_Click(object sender, EventArgs e)
        {
            DockContent dcnt = GetSelectedContent();
            if (dcnt != null && dcnt.GetType().Equals(typeof(QueryDocument)))
            {
                ((QueryDocument)dcnt).Comment(-1);
            }
        }

        private void toolBarIndent_Click(object sender, EventArgs e)
        {
            DockContent dcnt = GetSelectedContent();
            if (dcnt != null && dcnt.GetType().Equals(typeof(QueryDocument)))
            {
                ((QueryDocument)dcnt).Indent(1);
            }
        }

        private void toolBarOutIndent_Click(object sender, EventArgs e)
        {
            DockContent dcnt = GetSelectedContent();
            if (dcnt != null && dcnt.GetType().Equals(typeof(QueryDocument)))
            {
                ((QueryDocument)dcnt).Indent(-1);
            }
        }

        private void toolBarMinum_Click(object sender, EventArgs e)
        {
            DockContent dcnt = GetSelectedContent();
            if (dcnt != null && dcnt.GetType().Equals(typeof(QueryDocument)))
            {
                ((QueryDocument)dcnt).TSQLToLine();
            }
        }

        private void SysNewVersion_Click(object sender, EventArgs e)
        {
            string application_start_path = Trim(AppDomain.CurrentDomain.BaseDirectory);
            if (System.IO.File.Exists(string.Format("{0}\\Autoupgrade.EXE", application_start_path)))
            {
                System.Diagnostics.Process.Start(string.Format("{0}\\Autoupgrade.EXE", application_start_path));
                try
                {
                    System.Threading.Thread.Sleep(100);
                    Application.Exit();
                }
                catch (Exception ex)
                {
                    DevelopAssistant.Common.NLogger.WriteToLine(ex.Message, "错误", DateTime.Now, ex.Source, ex.StackTrace);
                    Environment.Exit(0);
                }
            }
        }

        private void toolBarButtonLogout_Click(object sender, EventArgs e)
        {
            try
            {
                CloseAllContents();
                dockPanel.SaveAsXml(configFile);
                System.Diagnostics.Process.Start(Application.ExecutablePath);
                Application.Exit();
            }
            catch (Exception ex)
            {
                System.Environment.Exit(0);
            }
        }        

    }

}
